﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Telerik.Web.Mvc;

namespace Presentation.Web.Admin.Controllers
{
    [HandleError]
    public class ArticleController : Infrastructure.Crosscutting.NetFramework.Controllers.BaseController
    {
        Application.Admin.Article.IArticleClassService claService;

        Application.Admin.Article.IArticleCommService commService;

        Application.Admin.Article.IArticleInfoClassService infoClaService;

        Application.Admin.Article.IArticlePicService articlePicService;

        Application.Admin.Article.IArticleService articleService;

        Application.Admin.Article.IArticleTagService tagService;

        Application.Admin.Sight.ISightPointService sightService;

        Application.Admin.Article.IArticleSightService articleSightService;

        Application.Admin.Pic.IPicInfoService picService;

        public ArticleController(Infrastructure.Crosscutting.NetFramework.IWorkContext work,
               Application.Admin.Article.IArticleClassService cla,
               Application.Admin.Article.IArticleCommService comm,
               Application.Admin.Article.IArticleInfoClassService infoCla,
               Application.Admin.Article.IArticlePicService articlePic,
               Application.Admin.Article.IArticleService article,
               Application.Admin.Article.IArticleTagService tag,
               Application.Admin.Sight.ISightPointService sight,
               Application.Admin.Article.IArticleSightService articleSight,
               Application.Admin.Pic.IPicInfoService pic)
            : base(work)
        {
            if (cla == null)
            {
                throw new ArgumentNullException("claService is null");
            }
            if (comm == null)
            {
                throw new ArgumentNullException("commService is null");
            }
            if (infoCla == null)
            {
                throw new ArgumentNullException("infoClaService is null");
            }
            if (articlePic == null)
            {
                throw new ArgumentNullException("articlePicService is null");
            }
            if (article == null)
            {
                throw new ArgumentNullException("articleService is null");
            }
            if (tag == null)
            {
                throw new ArgumentNullException("tagService is null");
            }
            if (sight == null)
            {
                throw new ArgumentNullException("sightService is null");
            }
            if (articleSight == null)
            {
                throw new ArgumentNullException("articleSightService is null");
            }
            if (pic == null)
            {
                throw new ArgumentNullException("picService is null");
            }
            claService = cla;
            commService = comm;
            infoClaService = infoCla;
            articlePicService = articlePic;
            articleService = article;
            tagService = tag;
            sightService = sight;
            articleSightService = articleSight;
            picService = pic;
        }

        #region article

        public ActionResult Index()
        {
            var data = this.GetArticleTrueState();
            return View(data.ToDto());
        }

        [GridAction]
        public JsonResult AjaxIndex(string searchKey)
        {
            var data = this.GetArticleTrueState();
            if (!string.IsNullOrEmpty(searchKey))
            {
                data = data.Where(e => e.Title.Contains(searchKey));
            }
            var dto = data.ToDto();
            var model = new GridModel<Domain.Dto.ArticleInfoDto>
            {
                Data = dto,
                Total = dto.Count()
            };
            return new JsonResult { Data = model, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }

        [HttpPost]
        public JsonResult Add(Domain.Dto.ArticleInfoDto dto, string sightName, int articleClass, int? isNotExpired)
        {
            var res = false;
            var message = "";
            if (string.IsNullOrEmpty(dto.Title) || string.IsNullOrEmpty(dto.Content))
            {
                message = "标题或内容不能为空";
            }
            else
            {
                dto.AddTime = System.DateTime.Now;
                dto.AudTime = null;
                //
                dto.Content = HttpUtility.HtmlDecode(dto.Content);
                dto.DeleteTime = null;
                dto.IpAddress = Infrastructure.Crosscutting.Comm.Service.StringService.GetRealIP();
                dto.IsAud = true;
                dto.IsDelete = false;
                dto.IsTop = false;
                dto.IsVouch = false;
                //dto.Remark
                //dto.Source
                //dto.SubTitle
                //dto.Title
                //dto.CustomDateTime
                //dto.ExpiredDateTime
                if (isNotExpired.HasValue && isNotExpired.Value == 1)
                {
                    dto.ExpiredDateTime = DateTime.Parse("2100-01-01");
                }
                dto.State = true;
                dto.SortNum = 0;
                dto.TopTime = null;
                dto.UserId = this.WorkContext != null ? this.WorkContext.CurrentUser.Id : 0;
                dto.UserName = this.WorkContext.CurrentUser != null ? this.WorkContext.CurrentUser.UserName : "";
                dto.ViewCount = 0;
                dto.VouchTime = null;
                var entity = dto.ToEntity();
                articleService.Add(entity, this.WorkContext.CurrentUser);
                res = entity.Id > 0 ? true : false;
                message = res ? "" : "添加失败了T_T";
                if (entity.Id > 0 && articleClass > 0)
                {
                    var cla = claService.Get(articleClass);
                    if (cla != null)
                    {
                        var infoCla = new Domain.Entity.ArticleInfoClass();
                        infoCla.AddTime = System.DateTime.Now;
                        infoCla.ArticleId = entity.Id;
                        infoCla.ClassId = cla.Id;
                        infoCla.IpAddress = Infrastructure.Crosscutting.Comm.Service.StringService.GetRealIP();
                        infoCla.SortNum = 0;
                        infoCla.State = true;
                        infoClaService.Add(infoCla, this.WorkContext.CurrentUser);
                    }
                    if (!string.IsNullOrEmpty(sightName))
                    {
                        var sightModel = sightService.GetList().Where(e => e.Name == sightName).FirstOrDefault();
                        if (sightModel != null && sightModel.Id > 0)
                        {
                            var articleSight = new Domain.Entity.ArticleSight();
                            articleSight.AddTime = System.DateTime.Now;
                            articleSight.ArticleId = entity.Id;
                            articleSight.IpAddress = Infrastructure.Crosscutting.Comm.Service.StringService.GetRealIP();
                            articleSight.SightId = sightModel.Id;
                            articleSight.SortNum = 0;
                            articleSight.State = true;
                            articleSightService.Add(articleSight, this.WorkContext.CurrentUser);
                        }
                    }
                }
            }
            return Json(new { success = res, message = message }, JsonRequestBehavior.AllowGet);
        }

        [GridAction]
        [HttpPost]
        public JsonResult Delete(int id)
        {
            var delete = articleService.Get(id);
            if (delete != null)
            {
                articleService.DeleteTrue(delete, this.WorkContext.CurrentUser);
            }
            var data = this.GetArticleTrueState().ToDto();
            return Json(data, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult MulDelete(FormCollection del)
        {
            var res = false;
            var message = "";
            var selectedList = del.GetValues("selectRow");
            if (selectedList != null && selectedList.Count() > 0)
            {
                res = articleService.DeleteTrue(selectedList.ToIntList(), this.WorkContext.CurrentUser);
                message = res == true ? "" : "删除失败了，T_T";
            }
            //返回空，是为了不再请求数据，因为他自己会重新binding的
            return Json(new { success = res, message = message }, JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        public ViewResult Edit(int id)
        {
            var data = articleService.Get(id);
            var sightName = (from arSight in articleSightService.GetList()
                             join sight in sightService.GetList() on arSight.SightId equals sight.Id
                             where arSight.ArticleId == id
                             select sight).Select(e => e.Name).FirstOrDefault();
            ViewBag.sightName = sightName;
            return View(data.ToDto());
        }

        [ValidateInput(false)]
        [HttpPost]
        public JsonResult Edit(Domain.Dto.ArticleInfoDto dto, string sightName, int articleClass, int? isNotExpired)
        {
            var res = false;
            var message = "";
            if (dto.Id > 0)
            {
                var entity = articleService.Get(dto.Id);
                if (entity != null && entity.Id > 0)
                {
                    entity.Remark = string.IsNullOrEmpty(dto.Remark) ? "" : dto.Remark.Trim();
                    entity.Source = string.IsNullOrEmpty(dto.Source) ? "" : dto.Source.Trim();
                    entity.SubTitle = string.IsNullOrEmpty(dto.SubTitle) ? "" : dto.SubTitle.Trim();
                    entity.Title = string.IsNullOrEmpty(dto.Title) ? "" : dto.Title.Trim();
                    entity.Content = HttpUtility.HtmlDecode(dto.Content);
                    entity.Content = entity.Content == null ? "" : entity.Content;
                    entity.CustomDateTime = string.IsNullOrEmpty(dto.CustomDateTime) ? "" : dto.CustomDateTime.Trim();
                    if (isNotExpired.HasValue && isNotExpired.Value == 1)
                    {
                        entity.ExpiredDateTime = DateTime.Parse("2100-01-01");
                    }
                    else
                    {
                        entity.ExpiredDateTime = dto.ExpiredDateTime.HasValue ? dto.ExpiredDateTime : null;
                    }
                    articleService.Modify(entity, this.WorkContext.CurrentUser);
                    res = true;

                    var infoCla = infoClaService.GetList()
                        .Where(e => e.ArticleId == entity.Id)
                        .OrderByDescending(e => e.Id)
                        .ThenByDescending(e => e.AddTime)
                        .FirstOrDefault();
                    if (infoCla != null)
                    {
                        infoCla.ClassId = articleClass;
                        infoClaService.Modify(infoCla, this.WorkContext.CurrentUser);
                    }
                    else
                    {
                        infoCla = new Domain.Entity.ArticleInfoClass();
                        infoCla.AddTime = System.DateTime.Now;
                        infoCla.ArticleId = entity.Id;
                        infoCla.ClassId = articleClass;
                        infoCla.IpAddress = Infrastructure.Crosscutting.Comm.Service.StringService.GetRealIP();
                        infoCla.SortNum = 0;
                        infoCla.State = true;
                        infoClaService.Add(infoCla, this.WorkContext.CurrentUser);
                    }

                    var sightModel = sightService.GetList().Where(e => e.Name == sightName).FirstOrDefault();
                    if (sightModel != null)
                    {
                        var articleSight = articleSightService.GetList().Where(e => e.ArticleId == entity.Id).FirstOrDefault();
                        if (articleSight != null)
                        {
                            articleSight.SightId = sightModel.Id;
                            articleSightService.Modify(articleSight, this.WorkContext.CurrentUser);
                        }
                        else
                        {
                            articleSight = new Domain.Entity.ArticleSight();
                            articleSight.AddTime = System.DateTime.Now;
                            articleSight.ArticleId = entity.Id;
                            articleSight.IpAddress = Infrastructure.Crosscutting.Comm.Service.StringService.GetRealIP();
                            articleSight.SightId = sightModel.Id;
                            articleSight.SortNum = 0;
                            articleSight.State = true;
                            articleSightService.Add(articleSight, this.WorkContext.CurrentUser);
                        }
                    }
                    else
                    {
                        var articleSight = articleSightService.GetList().Where(e => e.ArticleId == entity.Id).FirstOrDefault();
                        if (articleSight != null)
                        {
                            articleSight.SightId = 0;
                            articleSightService.Modify(articleSight, this.WorkContext.CurrentUser);
                        }
                    }
                }
                else
                {
                    message = "没有找到要修改的对象！！！";
                }
            }
            return Json(new { success = res, message = message }, JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        public JsonResult Search(string term)
        {
            if (!string.IsNullOrEmpty(term))
            {
                var data = this.GetArticleTrueState().Where(e => e.Title.Contains(term.Trim()))
                            .OrderBy(e => e.Id).Take(10)
                            .Select(e => e.Title).Distinct();
                return Json(data.ToList(), JsonRequestBehavior.AllowGet);
            }
            else
            {
                var data = this.GetArticleTrueState().OrderBy(e => e.Id).Take(10)
                            .Select(e => e.Title).Distinct();
                return Json(data.ToList(), JsonRequestBehavior.AllowGet);
            }
        }

        #endregion

        #region article pic pre view

        public JsonResult ArticlePicView(int id)
        {
            var res = false;
            var path = "";
            var message = "";
            var width = 0;
            var height = 0;
            var picId = articlePicService.GetList().Where(e => e.ArticleId == id)
                .OrderByDescending(e => e.Id)
                .ThenByDescending(e => e.AddTime)
                .Select(e => e.PicInfoId)
                .FirstOrDefault();
            var pic = picService.Get(picId);
            if (pic != null)
            {
                path = pic.WebFullPath;
                var phyPath = Server.MapPath("~" + path);
                var exist = System.IO.File.Exists(phyPath);
                if (exist)
                {
                    System.Drawing.Image image = System.Drawing.Image.FromFile(phyPath);
                    if (image != null)
                    {
                        width = image.Width;
                        height = image.Height;
                        image.Dispose();
                    }
                    res = true;
                }
                else
                {
                    message = "物理文件已经被删除了";
                }
            }
            else
            {
                message = "没有找到，你要浏览的图片地址T_T！，快去添加一张吧！";
            }
            return Json(new { success = res, width = width, height = height, path = path, message = message }, JsonRequestBehavior.AllowGet);
        }

        #endregion


        #region util

        protected IQueryable<Domain.Entity.ArticleInfo> GetArticleTrueState()
        {
            var data = articleService.GetList().Where(e => e.State == true)
                .OrderByDescending(e => e.Id);
            return data;
        }

        #endregion
    }
}
